import { _decorator, Animation, Component, EventMouse, Input, input, Node, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PlayerController')
export class PlayerController extends Component {
    private _startJump = false;
    private _jumpSpeed: number = 0;
    private _jumpTime = 0.2;
    private _curJumptime = 0;
    private _targetPos = new Vec3();
    private _curTotalStep:number = 0;

    @property(Animation)
    public bodyAnim: Animation = null;
    
    start() {
        
    }

    setIsCanControl(value:boolean){
        if(value)
            input.on(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
        else
            input.off(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
    }

    onMouseDown(event: EventMouse){
        if(event.getButton()==0){
            this.jumpByStep(1);
        }else if(event.getButton()==2){
            this.jumpByStep(2);
        }

    }
    jumpByStep(step:number){
        if(this._startJump) 
            return;
        
        const animName = (step==1)?'jumpOneStep':'jumpTwoStep';
        this.bodyAnim.play(animName);
        
        this._jumpTime = this.bodyAnim.getState(animName).duration;
        
        this._startJump = true;
        this._curJumptime = 0;
        this._jumpSpeed = 40*step/this._jumpTime;
        
        Vec3.add(this._targetPos, this.node.position, new Vec3(40*step, 0, 0));
        this._curTotalStep += step;
    }
    protected update(dt: number): void {
        if(this._startJump){
            this._curJumptime += dt;
            if(this._curJumptime > this._jumpTime){
                this._startJump = false;
                this._curJumptime = 0;
                this.node.setPosition(this._targetPos);
                this.node.emit('JumpEnd', this._curTotalStep);
            }else{
                const curPos = this.node.position;
                this.node.setPosition(curPos.x + dt*this._jumpSpeed, curPos.y, curPos.z);
            }
        }
    }
    reset(){
        this.node.setPosition(0, 0, 0);
        this._startJump = false;
        this._jumpSpeed = 0;
        this._curTotalStep = 0;
    }

    protected onDestroy(): void {
        input.off(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
    }
}


